package com.app.business.web.business;

import com.app.business.en.Status;
import com.app.business.model.AzProject;
import com.app.business.model.ShopHouse;
import com.app.business.service.AzProjectService;
import com.app.business.service.ShopHouseService;
import com.app.system.jpa.PageBean;
import com.app.system.log4j2.LogUtils;
import com.app.system.permission.model.DataDict;
import com.app.system.permission.service.DataDictService;
import com.app.system.utils.CollectionUtils;
import com.app.system.utils.ParamUtils;
import com.app.system.utils.WebUtils;
import com.app.system.utils.dataType.BigDecimalUtils;
import com.app.system.utils.dataType.DateUtils;
import com.app.system.utils.dataType.IntegerUtils;
import com.app.system.utils.dataType.StringUtils;
import com.app.system.utils.exception.Precondition;
import com.app.system.utils.exception.Response;
import com.app.system.utils.page.LayUiUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import freemarker.template.Configuration;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import java.util.*;

/**
 * 店铺管理
 * Created by ddz on 2021/12/06 14:49.
 *
 * @author lsh
 */
@Controller
@RequestMapping("/business/shopHouse/*")
public class ShopHouseController {

    @Resource
    private ShopHouseService shopHouseService;
    @Resource
    private DataDictService dataDictService;
    @Resource
    private AzProjectService azProjectService;
    private Logger logger = LogUtils.getBusinessLogger();

    @Autowired
    private Configuration freemarkerConfiguration; // 注入bean，这里是属性注入，推荐构造注入

    /**
     * 店铺数据管理列表
     */
    @RequestMapping("shopHouseList")
    @RequiresPermissions("shopHouse:shopHouseList")
    public void shopHouseList(HttpServletRequest request, ModelMap modelMap) {
        Integer projectId = ParamUtils.getInt(request, "azProjectId", 0);
        AzProject azProject = this.azProjectService.findOne(projectId);
        modelMap.addAttribute("azProject", azProject);
    }

    /**
     * 加载店铺信息数据
     *
     * @return
     */
    @RequestMapping("loadShopHouseList")
    @ResponseBody
    @RequiresPermissions("shopHouse:loadShopHouseList")
    public Map loadShopHouseList(HttpServletRequest request) {
        Integer projectId = ParamUtils.getInt(request, "azProjectId", 0);
        List<Map> listData = Lists.newArrayList();
        PageBean<ShopHouse> shopHousePageBean = this.shopHouseService.shopHouseListByProjectId(projectId);
        List<ShopHouse> shopHouseList = shopHousePageBean.getDatas();
        Map<String, DataDict> houseStatusMap = this.dataDictService.getMapByParentNameForValue("房源状态");
        if (!CollectionUtils.isEmpty(shopHouseList)) {
            Map<String, Object> item = null;
            for (ShopHouse shopHouse : shopHouseList) {
                item = null;
                item = Maps.newHashMap();
                item.put("id", shopHouse.getId());
                item.put("buildNum", StringUtils.getNotNull(shopHouse.getBuildNum()));
                item.put("houseNum", StringUtils.getNotNull(shopHouse.getHouseNum()));
                item.put("floor", IntegerUtils.getNotNull(shopHouse.getFloor()));
                item.put("buildArea", BigDecimalUtils.getNotNullStr(shopHouse.getBuildArea()));
                item.put("poolArea", BigDecimalUtils.getNotNullStr(shopHouse.getPoolArea()));
                item.put("houseStatus", shopHouse.getHouseStatus());
                item.put("houseStatusStr", StringUtils.dataDictShow(houseStatusMap.get(shopHouse.getHouseStatus().toString())));
                item.put("chooseHouseDate", DateUtils.dateToStringDefault(shopHouse.getChooseHouseDate()));
                item.put("zhBl", shopHouse.getZhBl());
                item.put("szZhArea", shopHouse.getSxZhArea());
                item.put("memo", shopHouse.getMemo());
                listData.add(item);
            }
        }
        return LayUiUtils.page(shopHousePageBean.getTotalCount().intValue(), listData);
    }

    /**
     * 店铺信息导出
     */
    @RequestMapping("shopHouseListExcel")
    @RequiresPermissions("shopHouse:shopHouseListExcel")
    public void shopHouseListExcel(HttpServletRequest request, HttpServletResponse response) {
        Integer projectId = ParamUtils.getInt(request, "azProjectId", 0);
        PageBean<ShopHouse> shopHousePageBean = this.shopHouseService.shopHouseExcelListByProjectId(projectId);
        List<ShopHouse> shopHouseList = shopHousePageBean.getDatas();
        Map<String, DataDict> houseStatusMap = this.dataDictService.getMapByParentNameForValue("房源状态");
        try {
            // 封装导出数据
            Map data = Maps.newHashMap();
            data.put("shopHouseList", shopHouseList);
            data.put("houseStatusMap", houseStatusMap);
            data.put("exportPerson", SecurityUtils.getSubject().getPrincipal());   //导出人姓名
            data.put("exportTime", DateUtils.dateToStringFormat(new Date(), "yyyy-MM-dd HH:mm:ss"));   //导出时间
//            data.put("decisions", exportDecisionList); //第二个worksheet的数据对象
            request.setCharacterEncoding("UTF-8");
            response.setContentType("application/x-download;");
            response.setHeader("Content-disposition", "attachment; filename=" + new String(("店铺数据导出.xls").getBytes(), "iso-8859-1"));
            freemarkerConfiguration.getTemplate("/business/shopHouse/shopHouseListExcel.ftl").process(data, response.getWriter());
        } catch (Exception e) {
            logger.error("文件下载异常", e);
            e.printStackTrace();
        }
    }

    /**
     * 店铺房源管理
     *
     * @param request
     * @param modelMap
     */
    @RequestMapping("shopHouseForm")
    @RequiresPermissions("shopHouse:shopHouseForm")
    public void shopHouseForm(HttpServletRequest request, ModelMap modelMap) {
        Integer shopHouseId = ParamUtils.getInt(request, "shopHouseId", 0);
        Integer azProjectId = ParamUtils.getInt(request, "azProjectId", 0);

        ShopHouse shopHouse = this.shopHouseService.findOne(shopHouseId);
        AzProject azProject = azProjectService.findOne(azProjectId);
        shopHouse = shopHouse == null ? new ShopHouse() : shopHouse;
        Precondition.checkSqdsArguement(azProject != null, "找不到所属安置项目！");

        modelMap.addAttribute("shopHouse", shopHouse);
        modelMap.addAttribute("azProject", azProject);
    }


    /**
     * 店铺信息保存
     *
     * @param request
     * @return
     */
    @RequestMapping("shopHouseSave")
    @ResponseBody
    @RequiresPermissions("shopHouse:shopHouseSave")
    public Response shopHouseSave(HttpServletRequest request) {
        Integer shopHouseId = ParamUtils.getInt(request, "shopHouseId", 0);
        Integer azProjectId = ParamUtils.getInt(request, "azProjectId", 0);
        ShopHouse shopHouse = this.shopHouseService.findOne(shopHouseId);
        AzProject project = azProjectService.findOne(azProjectId);
        Precondition.checkAjaxArguement(project != null, "0012", "项目不存在");

        if (shopHouse == null) {
            shopHouse = new ShopHouse();
        }
        Precondition.checkAjaxArguement(shopHouse.getHouseStatus() == null || !shopHouse.getHouseStatus().equals(2), "0011", "店铺已选，不能修改");
        WebUtils.bind(request, shopHouse);
        shopHouse.setAzProject(project);
        shopHouseService.save(shopHouse);

        Response response = new Response();
        response.setCode("0001");
        response.setData(project.getId());
        return response;
    }


    /**
     * 删除店铺房源
     *
     * @param request
     * @return
     */
    @RequestMapping("deleteShopHouse")
    @ResponseBody
    @RequiresPermissions("shopHouse:deleteShopHouse")
    public Response deleteShopHouse(HttpServletRequest request) {
        Integer shopHouseId = ParamUtils.getInt(request, "shopHouseId", 0);
        ShopHouse shopHouse = this.shopHouseService.findOne(shopHouseId);
        Precondition.checkAjaxArguement(shopHouse != null, "1111", "数据错误！");
        Precondition.checkAjaxArguement(shopHouse.getHouseStatus() != null && shopHouse.getHouseStatus() != 2, "1111", "店铺已选择，不可删除！");
        this.shopHouseService.delete(shopHouse.getId());
        return new Response("0001", "操作成功");
    }

    /**
     * 导入页面
     *
     * @param request
     * @param modelMap
     */
    @RequestMapping("importPage")
    @RequiresPermissions("shopHouse:importPage")
    public void importPage(HttpServletRequest request, ModelMap modelMap) {
        Integer projectId = ParamUtils.getInt(request, "azProjectId", 0);
        AzProject azProject = this.azProjectService.findOne(projectId);
        Precondition.checkAjaxArguement(azProject != null, "9999", "导入的安置项目不存在");
        modelMap.addAttribute("azProject", azProject);
    }


    /**
     * 导入店铺数据
     *
     * @param request
     * @return
     * @throws Exception
     */
    @Transactional
    @RequestMapping("importShopHouse")
    @ResponseBody
    @RequiresPermissions("shopHouse:importShopHouse")
    public Response importShopHouse(HttpServletRequest request) {
        Integer projectId = ParamUtils.getInt(request, "azProjectId", 0);
        AzProject azProject = this.azProjectService.findOne(projectId);
        Precondition.checkAjaxArguement(azProject != null, "9999", "导入的安置项目不存在");

        String shopHouses = request.getParameter("shopHouseArray");
        String[] shopHouseArray = shopHouses.split("\r\n");

        //Set<安置项目-幢号-户号-所在层数>
        Set<String> shopHouseSet = this.shopHouseService.findShopHouseSetByAzProjectId(azProject.getId());

        //buildNum:幢号，houseNum:户号，floor：所在层数，buildArea：建筑面积，poolArea:公摊面积,shopHousePrice:店铺单价,shopHouseMoney:店铺总价,zhBl:所需置换比例,sxZhArea:所需置换面积,houseStatus:店铺状态,memo：备注
        String buildNum = null, houseNum = null, floor = null, buildArea = null, poolArea = null, shopHousePrice = null, shopHouseMoney = null, zhBl = null, sxZhArea = null, houseStatus = null, memo = null;

        ShopHouse shopHouse = null;
        //待导入的房源数据
        List<ShopHouse> importShopHouseList = new ArrayList<>();

        String[] rowObj = null;
        String excelStorage = null;
        int rowObjLength = 0;//每条数据的列数
        int errorCount = 0;//错误数据数量
        StringBuffer msg = new StringBuffer();
        int index = 0;
        for (String shopHouseInfo : shopHouseArray) {
            rowObj = null;
            rowObj = shopHouseInfo.split("\t");
            rowObjLength = rowObj.length;
            Precondition.checkAjaxArguement(rowObjLength == 11, "0012", "请确认每列都有数据！");
            if (rowObj.length == 0) {
                continue;
            }

            index = 0;
            buildNum = rowObj[index]; //幢号
            index++;
            houseNum = rowObj[index]; //户号
            index++;
            floor = rowObj[index]; //所在层数
            index++;
            buildArea = rowObj[index]; //建筑面积
            index++;
            poolArea = rowObj[index]; //公摊面积
            index++;
            shopHousePrice = rowObj[index];//店铺单价
            index++;
            shopHouseMoney = rowObj[index];//店铺总价
            index++;
            zhBl = rowObj[index];//所需置换比例
            index++;
            sxZhArea = rowObj[index];//所需置换面积
            index++;
            houseStatus = rowObj[index];//店铺状态
            index++;
            memo = rowObj[index];//备注

            excelStorage = projectId + "-" + buildNum + "-" + houseNum + "-" + floor;

            if (StringUtils.isEmpty(excelStorage)) {
                continue;
            }
            //只导入不存在的房源
            if (shopHouseSet.contains(excelStorage)) {
                errorCount++;
                msg.append("<br/>" + shopHouseInfo + ",");
                //已经存在的数据输出到页面
                continue;
            }

            shopHouse = new ShopHouse();
            shopHouse.setHouseStatus(1);
            shopHouse.setAzProject(azProject);
            shopHouse.setBuildNum(buildNum);
            shopHouse.setHouseNum(houseNum);
            shopHouse.setFloor(Integer.valueOf(floor));
            shopHouse.setBuildArea(BigDecimalUtils.stringToBigDecimal(buildArea));
            shopHouse.setPoolArea(BigDecimalUtils.stringToBigDecimal(poolArea));
            shopHouse.setShopHousePrice(BigDecimalUtils.stringToBigDecimal(shopHousePrice));
            shopHouse.setShopHouseMoney(BigDecimalUtils.stringToBigDecimal(shopHouseMoney));
            shopHouse.setZhBl(BigDecimalUtils.stringToBigDecimal(zhBl));
            shopHouse.setSxZhArea(BigDecimalUtils.stringToBigDecimal(sxZhArea));
            shopHouse.setHouseStatus(houseStatus != null && !houseStatus.equals("") ? IntegerUtils.stringToInteger(houseStatus) : Status.NO.getIndex());

            shopHouse.setMemo(memo);

            importShopHouseList.add(shopHouse);
        }
        this.shopHouseService.batchSave(importShopHouseList);
        String successInfo = "插入" + importShopHouseList.size() + "条数据;";
        if (errorCount > 0) {
            successInfo = successInfo + "失败" + errorCount + "条，如下：";
        }
        msg = msg.length() == 0 ? msg : msg.replace(0, msg.length(), msg.toString()).append("<br/>数据已存在，无法导入");
        System.out.println(successInfo + msg.toString());
        Response response = new Response("0001", successInfo + msg.toString());
        return response;
    }

}
